package com.core.utils;

import com.google.common.collect.Sets;
import org.springframework.lang.Nullable;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;

public class BeanUtils extends org.springframework.beans.BeanUtils {
    /**
     * 判断两个相同类型的实例是否拥有相同的属性
     *
     * @return
     */
    public static <T> boolean hasSameProperties(T x, T y, @Nullable String... ignoreProperties) {
        if (x == null || y == null) {
            return false;
        }
        Set<String> ignoreNames = Sets.newHashSet();
        if (ignoreProperties != null && ignoreProperties.length > 0) {
            ignoreNames.addAll(Arrays.asList(ignoreProperties));
        }
        PropertyDescriptor[] targetPds = getPropertyDescriptors(x.getClass());
        for (PropertyDescriptor targetPd : targetPds) {
            Method readMethod = targetPd.getReadMethod();
            if (readMethod == null) {
                continue;
            }
            if (ignoreNames.contains(targetPd.getName())) {
                continue;
            }
            try {
                Object xValue = readMethod.invoke(x);
                Object yValue = readMethod.invoke(y);
                if (xValue == null && yValue == null) {
                    continue;
                }
                if (xValue == null || yValue == null) {
                    return false;
                }
                if (!xValue.equals(yValue)) {
                    return false;
                }
            } catch (Throwable e) {
                throw new RuntimeException("获取值失败", e);
            }
        }
        return true;
    }
}
